<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use Cache,Event,Auth,Excel;
class BaoanController extends Controller
{
    public function messages($table){
        if($table == 'gudong'){
            return [
                'unit_name.required' => '单位名不能为空',
                'name.required'  => '姓名不能为空',
                'sex.required' => '性别不能为空',
                'birthday.required' => '出生年月不能为空',
                'nation.required' => '民族不能为空',
                'native_place.required' => '籍贯不能为空',
                'education.required' => '文化程度不能为空',
                'political_status.required' => '政治面貌不能为空',
                'id_number.regex' => '身份证号格式错误',
                'jine.required'=> '出资金额不能为空',
                'bili.required'=> '出资比例不能为空',
                'email.email' => '邮箱格式错误',
                'phone.regex' => '联系电话格式错误',
            ];
        }
        if($table == 'guanli'){
            return [
                'unit_name.required' => '单位名不能为空',
                'name.required'  => '姓名不能为空',
                'sex.required' => '性别不能为空',
                'birthday.required' => '出生年月不能为空',
                'nation.required' => '民族不能为空',
                'native_place.required' => '籍贯不能为空',
                'education.required' => '文化程度不能为空',
                'political_status.required' => '政治面貌不能为空',
                'id_number.regex' => '身份证号格式错误',
                'email.email' => '邮箱格式错误',
                'phone.regex' => '联系电话格式错误',
            ];
        }
        if($table == 'baoan'){
            return [
                'name.required'  => '姓名不能为空',
                'sex.required' => '性别不能为空',
                'birthday.required' => '出生年月不能为空',
                'nation.required' => '民族不能为空',
                'native_place.required' => '籍贯不能为空',
                'education.required' => '文化程度不能为空',
                'political_status.required' => '政治面貌不能为空',
                'id_number.regex' => '身份证号格式错误',
                'email.email' => '邮箱格式错误',
                'phone.regex' => '联系电话格式错误',
            ];
        }
        if($table == 'kaohe'){
            return [
                'kaoheren.required'  => '考核人不能为空',
                'kaohe_time.required' => '考核时间不能为空',
                'yanzhongshigu.required'  => '严重安全事故数量不能为空',
                'yibanshigu.required' => '一般安全事故数量不能为空',
            ];
        }
    }

    public function index(request $request)
    {
        if($request->rows) {
            //如果是民警登录，只能查看自己辖区的单位
            if(Auth::guard('admin')->user()->org_id != null && Auth::guard('admin')->user()->dengji == 4){
                $map['baoan_company.org_id'] = Auth::guard('admin')->user()->org_id;
            }
            //如果是企业用户
            if(Auth::guard('admin')->user()->role_id == 22){
                $map['baoan_company.id'] = Auth::guard('admin')->user()->unit_id;
            }
            if($request->city != null){
                if($request->city == 0){

                }else{
                    $map['baoan_company.city'] = $request->city;
                }
            }
            if($request->area){
                $map['baoan_company.area'] = $request->area;
            }
            if($request->org_id){
                $map['baoan_company.org_id'] = $request->org_id;
            }
            if($request->name){
                $map[] = array('baoan_company.name','like','%'.$request->name.'%');
            }
            if($request->lianxiren){
                $map['baoan_company.lianxiren'] = $request->lianxiren;
            }
            $map['baoan_company.is_del'] = '0';
            $res = DB::table('baoan_company')
                ->where($map)
                ->leftJoin('area as a', 'baoan_company.city', '=', 'a.id')
                ->leftJoin('area as b', 'baoan_company.area', '=', 'b.id')
                ->leftJoin('area as c', 'baoan_company.org_id', '=', 'c.id')
                ->leftJoin('admin_users as e', 'baoan_company.user_id', '=', 'e.id')
                ->select('baoan_company.*', 'a.name as city', 'b.name as area', 'c.name as org_id', 'e.name as user_id')
                ->paginate($request->rows);
            $list = $res->items();
            foreach ($list as $k=>$v){
                if($v->is_hege == 1){
                    $list[$k]->is_hege = '合格';
                }elseif($v->is_hege == 2){
                    $list[$k]->is_hege = '不合格';
                }else{
                    $list[$k]->is_hege = '暂未考核';
                }
            }
            $result['total'] = $res->total();
            $result['rows'] = $list;
            echo json_encode($result);
        }else{
            $city = db::table('area')->where('dengji','=','1')->orderby('id')->get();//市
            return view('admin.baoan.index', ['city' => $city]);
        }
    }

    public function index2(request $request)
    {
        if($request->rows) {
            //如果是民警登录，只能查看自己辖区的单位
            if(Auth::guard('admin')->user()->org_id != null && Auth::guard('admin')->user()->dengji == 4){
                $map['baoan_company.org_id'] = Auth::guard('admin')->user()->org_id;
            }
            //如果是企业用户
            if(Auth::guard('admin')->user()->role_id == 22){
                $map['baoan_company.id'] = Auth::guard('admin')->user()->unit_id;
            }
            if($request->city != null){
                if($request->city == 0){

                }else{
                    $map['baoan_company.city'] = $request->city;
                }
            }
            if($request->area){
                $map['baoan_company.area'] = $request->area;
            }
            if($request->org_id){
                $map['baoan_company.org_id'] = $request->org_id;
            }
            if($request->name){
                $map[] = array('baoan_company.name','like','%'.$request->name.'%');
            }
            if($request->lianxiren){
                $map['baoan_company.lianxiren'] = $request->lianxiren;
            }
            $map['baoan_company.is_del'] = '0';
            $res = DB::table('baoan_company')
                ->where($map)
                ->leftJoin('area as a', 'baoan_company.city', '=', 'a.id')
                ->leftJoin('area as b', 'baoan_company.area', '=', 'b.id')
                ->leftJoin('area as c', 'baoan_company.org_id', '=', 'c.id')
                ->leftJoin('admin_users as e', 'baoan_company.user_id', '=', 'e.id')
                ->select('baoan_company.*', 'a.name as city', 'b.name as area', 'c.name as org_id', 'e.name as user_id')
                ->paginate($request->rows);
            $list = $res->items();
            foreach ($list as $k=>$v){
                if($v->is_hege == 1){
                    $list[$k]->is_hege = '合格';
                }elseif($v->is_hege == 2){
                    $list[$k]->is_hege = '不合格';
                }else{
                    $list[$k]->is_hege = '暂未考核';
                }
            }
            $result['total'] = $res->total();
            $result['rows'] = $list;
            echo json_encode($result);
        }else{
            $city = db::table('area')->where('dengji','=','1')->orderby('id')->get();//市
            return view('admin.baoan.index2', ['city' => $city]);
        }
    }

    public function add(Request $request)
    {
        if($request->isMethod('post')){
            if(Input::get('city') && Input::get('area') && Input::get('org_id')){
                $data = Input::except('_token','fanwei');
                if(Input::has('fanwei')){
                    $arr = Input::get('fanwei');
                    $permission_id = '';
                    foreach ($arr as $v => $k) {
                        $permission_id .= $k . ',';
                    }
                    $data['fanwei'] = substr($permission_id, 0, -1);
                }
                if($request['pic']){
                    $images = $request['pic'];
                    $filedir = "upload/baoan/".date('Y-m-d',time())."/";
                    $extension = $images -> getClientOriginalExtension();
                    $newImagesName=md5(time()).random_int(5,5).".".$extension;
                    $images->move($filedir,$newImagesName);
                    $data['pic'] = $filedir.$newImagesName;
                }
                $data['user_id'] = Auth::guard('admin')->user()->id;
                $data['created_at'] = date('Y-m-d H:i:s',time());
                $data['updated_at'] = date('Y-m-d H:i:s',time());
                foreach ($data as $k=>$v){
                    $data[$k] = htmlspecialchars($v);
                }
                DB::table('baoan_company')->insert($data);
                return ['status'=>1,'msg'=>'添加成功'];
                //return redirect('admin/units/index/');
            }else{
                return ['status'=>0,'msg'=>'请选择正确的市、区、派出所'];
                /*echo "<script>alert('请选择正确的市、区、派出所');window.history.go(-1);</script>";
                exit();*/
            }

        }
        //类型
        $type = db::table('unit_type')->where('is_del','0')->get();
        //市
        $city = db::table('area')->where('dengji','=','1')->orderby('id')->get();
        return view('admin.baoan.add', ['type'=>$type,'city' => $city]);
    }

    public function tab($id)
    {
        return view('admin.baoan.tab', ['id' => $id]);
    }

    public function tab2($id)
    {
        return view('admin.baoan.tab2', ['id' => $id]);
    }

    public function edit($id,Request $request)
    {
        $re = DB::table('baoan_company')->where('id',$id)->first();
        $re->fanwei = explode(",",$re->fanwei);
        if($request->isMethod('post')){
            $obj = DB::table('baoan_company');
            $data = Input::except('_token','fanwei');
            if(Input::has('fanwei')){
                $arr = Input::get('fanwei');
                $permission_id = '';
                foreach ($arr as $v => $k) {
                    $permission_id .= $k . ',';
                }
                $data['fanwei'] = substr($permission_id, 0, -1);
            }
            if($request['pic']){
                $images = $request['pic'];
                $filedir = "upload/baoan/".date('Y-m-d',time())."/";
                $extension = $images -> getClientOriginalExtension();
                $newImagesName=md5(time()).random_int(5,5).".".$extension;
                $images->move($filedir,$newImagesName);
                $data['pic'] = $filedir.$newImagesName;
            }
            if($data['org_id']){
                $area = DB::table('area')->where('id','=',$data['org_id'])->value('cid');
                if($area != $data['area']){
                    return ['status'=>0,'msg'=>'系统错误，请重新操作'];
                    /*echo "<script>alert('系统错误，请重新操作');window.history.go(-1);</script>";
                    exit();*/
                }
            }else{
                $data['org_id'] = $re->org_id;
                $data['area'] = $re->area;
                $data['city'] = $re->city;
            }

            if($data['area']){
                $city = DB::table('area')->where('id','=',$data['area'])->value('cid');
                if($city != $data['city']){
                    return ['status'=>0,'msg'=>'系统错误，请重新操作'];
                    /*echo "<script>alert('系统错误，请重新操作');window.history.go(-1);</script>";
                    exit();*/
                }
            }else{
                $data['area'] = $re->area;
            }

            if(!$data['city']){
                $data['city'] = $re->city;
            }
            foreach ($data as $k=>$v){
                $data[$k] = htmlspecialchars($v);
            }
            $obj->where('id',$id)->update($data);
            return ['status'=>1,'msg'=>'编辑成功'];
            //return redirect('admin/units/index/');
        }
        //市
        $city = db::table('area')->where('dengji','=','1')->orderby('id')->get();
        //股东
        $gudong = db::table('gudong')->where('unit_id',$id)->get();
        $gudong_count = db::table('gudong')->where('unit_id',$id)->count();
        //管理
        $guanli = db::table('guanli')->where('unit_id',$id)->get();
        $guanli_count = db::table('guanli')->where('unit_id',$id)->count();
        return view('admin.baoan.edit', ['re' => $re,'city' => $city,'id' => $id,'gudong'=>$gudong,'gudong_count'=>$gudong_count,'guanli'=>$guanli,'guanli_count'=>$guanli_count]);
    }

    public function del($id)
    {
        $re = db::table('baoan_company')->where('id',$id)->delete();
        if($re){
            return ['status'=> 1,'msg'=>'删除成功'];
        }else{
            return ['status'=> 0,'msg'=>'删除失败'];
        }
        //return redirect()->back();
    }

    public function faren($id,request $request)
    {
        if($request->rows) {
            $map['unit_id'] = $id;
            $res = DB::table('baoan_faren')->where($map)->orderby('id','desc')->paginate($request->rows);
            $list = $res->items();
            $result['total'] = $res->total();
            $result['rows'] = $list;
            echo json_encode($result);
        }else{
            return view('admin.baoan.faren', ['id'=>$id]);
        }
    }

    public function add_faren(Request $request,$id)
    {
        if($request->isMethod('post')){
            $this->validate($request, [
                'unit_name' => 'required',
                'name' => 'required',
                'sex' => 'required',
                'birthday' => 'required',
                'nation' => 'required',
                'native_place' => 'required',
                'education' => 'required',
                'political_status' => 'required',
                'id_number' =>array('regex:/^(\d{15}$|^\d{18}$|^\d{17}(\d|X|x))$/'),
                'email' =>'nullable|email',
                'phone' =>array('regex:/^((0\d{2,3}-\d{7,8})|(1[3584]\d{9}))$/'),
            ],$this->messages('guanli'));
            $data = Input::except('_token');
            if($request['pic']){
                $images = $request['pic'];
                $filedir = "upload/baoan/".date('Y-m-d',time())."/";
                $extension = $images -> getClientOriginalExtension();
                $newImagesName=md5(time()).random_int(5,5).".".$extension;
                $images->move($filedir,$newImagesName);
                $data['pic'] = $filedir.$newImagesName;
            }
            $data['unit_id'] = $id;
            $data['user_id'] = Auth::guard('admin')->user()->id;
            $data['created_at'] = date('Y-m-d H:i:s',time());
            $data['updated_at'] = date('Y-m-d H:i:s',time());
            $id = DB::table('baoan_faren')->insert($data);
            if($id){
                return ['msg'=>'添加成功'];
            }else{
                return ['msg'=>'添加失败'];
            }
            //return redirect('admin/units/faren/'.$id);
        }
        //民族
        $nation = db::table('nation')->get();
        return view('admin.baoan.add_faren', ['nation' => $nation,'id' => $id]);
    }

    public function edit_faren($id,Request $request)
    {
        if($request->isMethod('post')){
            $this->validate($request, [
                'unit_name' => 'required',
                'name' => 'required',
                'sex' => 'required',
                'birthday' => 'required',
                'nation' => 'required',
                'native_place' => 'required',
                'education' => 'required',
                'political_status' => 'required',
                'id_number' =>array('regex:/^(\d{15}$|^\d{18}$|^\d{17}(\d|X|x))$/'),
                'email' =>'nullable|email',
                'phone' =>array('regex:/^((0\d{2,3}-\d{7,8})|(1[3584]\d{9}))$/'),
            ],$this->messages('guanli'));
            $data = Input::except('_token');
            if($request['pic']){
                $images = $request['pic'];
                $filedir = "upload/baoan/".date('Y-m-d',time())."/";
                $extension = $images -> getClientOriginalExtension();
                $newImagesName=md5(time()).random_int(5,5).".".$extension;
                $images->move($filedir,$newImagesName);
                $data['pic'] = $filedir.$newImagesName;
            }
            $data['user_id'] = Auth::guard('admin')->user()->id;
            $data['updated_at'] = date('Y-m-d H:i:s',time());
            $id = DB::table('baoan_faren')->where('id',$id)->update($data);
            if($id){
                return ['msg'=>'编辑成功'];
            }else{
                return ['msg'=>'编辑失败'];
            }
        }
        $re = DB::table('baoan_faren')->where('id',$id)->first();
        //民族
        $nation = db::table('nation')->get();
        return view('admin.baoan.edit_faren', ['re' => $re,'nation' => $nation,'id' => $id]);
    }

    public function del_faren($id)
    {
        $re = db::table('baoan_faren')->where('id',$id)->delete();
        if($re){
            return ['status'=> 1,'msg'=>'删除成功'];
        }else{
            return ['status'=> 0,'msg'=>'删除失败'];
        }
        //return redirect()->back();
    }

    public function baoan($id,request $request)
    {
        if($request->rows) {
            $map['unit_id'] = $id;
            $res = DB::table('baoan')->where($map)->paginate($request->rows);
            $list = $res->items();
            foreach ($list as $k=>$v){
                $list[$k]->dengji = getValue($v->dengji,'baoan_dengji' ,'id' ,'name' );
            }
            $result['total'] = $res->total();
            $result['rows'] = $list;
            echo json_encode($result);
        }else{
            return view('admin.baoan.baoan', ['id'=>$id]);
        }
    }

    public function add_baoan(Request $request,$id)
    {
        if($request->isMethod('post')){
            $this->validate($request, [
                'name' => 'required',
                'sex' => 'required',
                'birthday' => 'required',
                'nation' => 'required',
                'native_place' => 'required',
                'education' => 'required',
                'political_status' => 'required',
                'id_number' =>array('regex:/^(\d{15}$|^\d{18}$|^\d{17}(\d|X|x))$/'),
                'email' =>'nullable|email',
                'phone' =>array('regex:/^((0\d{2,3}-\d{7,8})|(1[3584]\d{9}))$/'),
            ],$this->messages('baoan'));
            $data = Input::except('_token');
            if($request['pic']){
                $images = $request['pic'];
                $filedir = "upload/baoan/".date('Y-m-d',time())."/";
                $extension = $images -> getClientOriginalExtension();
                $newImagesName=md5(time()).random_int(5,5).".".$extension;
                $images->move($filedir,$newImagesName);
                $data['pic'] = $filedir.$newImagesName;
            }
            $data['unit_id'] = $id;
            $data['user_id'] = Auth::guard('admin')->user()->id;
            $data['created_at'] = date('Y-m-d H:i:s',time());
            $data['updated_at'] = date('Y-m-d H:i:s',time());

            $re = DB::table('baoan')->insert($data);
            if($re){
                return ['msg'=>'保存成功'];
            }else{
                return ['msg'=>'保存失败'];
            }
            //return redirect('admin/units/baowei/'.$id);
        }
        //民族
        $nation = db::table('nation')->get();
        return view('admin.baoan.add_baoan', ['id'=>$id,'nation'=>$nation]);
    }

    public function edit_baoan($id,Request $request)
    {
        if($request->isMethod('post')){
            $this->validate($request, [
                'name' => 'required',
                'sex' => 'required',
                'birthday' => 'required',
                'nation' => 'required',
                'native_place' => 'required',
                'education' => 'required',
                'political_status' => 'required',
                'id_number' =>array('regex:/^(\d{15}$|^\d{18}$|^\d{17}(\d|X|x))$/'),
                'email' =>'nullable|email',
                'phone' =>array('regex:/^((0\d{2,3}-\d{7,8})|(1[3584]\d{9}))$/'),
            ],$this->messages('baoan'));
            $data = Input::except('_token');
            if($request['pic']){
                $images = $request['pic'];
                $filedir = "upload/baoan/".date('Y-m-d',time())."/";
                $extension = $images -> getClientOriginalExtension();
                $newImagesName=md5(time()).random_int(5,5).".".$extension;
                $images->move($filedir,$newImagesName);
                $data['pic'] = $filedir.$newImagesName;
            }
            $data['user_id'] = Auth::guard('admin')->user()->id;
            $data['updated_at'] = date('Y-m-d H:i:s',time());
            $re = DB::table('baoan')->where('id',$id)->update($data);
            //$cid = DB::table('baoweirenyuan')->where('id',$id)->value('unit_id');
            if($re){
                return ['msg'=>'编辑成功'];
            }else{
                return ['msg'=>'编辑失败'];
            }
            //return redirect('admin/units/baowei/'.$cid);
        }
        $re = DB::table('baoan')->where('id',$id)->first();
        $nation = db::table('nation')->get();
        return view('admin.baoan.edit_baoan', ['re' => $re,'id'=>$id,'nation'=>$nation]);
    }

    public function del_baoan($id)
    {
        $re = db::table('baoan')->where('id',$id)->delete();
        if($re){
            return ['status'=> 1,'msg'=>'删除成功'];
        }else{
            return ['status'=> 0,'msg'=>'删除失败'];
        }
        //return redirect()->back();
    }

    public function cailiao($id,Request $request){
        if($request->rows) {
            $res = DB::table('baoan_cailiao')->paginate($request->rows);
            $list = $res->items();
            $result['total'] = $res->total();
            $result['rows'] = $list;
            echo json_encode($result);
        }else{
            return view('admin.baoan.cailiao',['id'=>$id]);
        }
    }

    public function cailiao_list($id,$uid,Request $request){
        if($request->rows) {
            $map = array(
                'unit_id' => $uid,
                'cailiao_type' => $id,
            );
            $res = DB::table('baoan_file')->where($map)->paginate($request->rows);
            $list = $res->items();
            foreach ($list as $k=>$v){
                $list[$k]->user_id = getValue($v->user_id,'admin_users' ,'id' ,'name' );
            }
            $result['total'] = $res->total();
            $result['rows'] = $list;
            echo json_encode($result);
        }else{
            return view('admin.baoan.cailiao_list',['id'=>$id,'uid'=>$uid]);
        }
    }

    public function add_cailiao($id,$uid,Request $request)
    {
        if($request->isMethod('post')){
            $data = Input::except('_token');
            if($request['pic']){
                $size = $request['pic']->getSize();
                $images = $request['pic'];
                $filedir = "upload/baoan/".date('Y-m-d',time())."/";
                $extension = $images -> getClientOriginalExtension();
                $newImagesName=md5(time()).random_int(5,5).".".$extension;
                $images->move($filedir,$newImagesName);
                $data['name'] = $images->getClientOriginalName();
                $data['size'] = format_bytes($size);
                $data['pic'] = $filedir.$newImagesName;
                $data['cailiao_type'] = $id;
                $data['unit_id'] = $uid;
                $data['user_id'] = Auth::guard('admin')->user()->id;
                $data['created_at'] = date('Y-m-d H:i:s',time());
                $data['updated_at'] = date('Y-m-d H:i:s',time());
                $id = DB::table('baoan_file')->insert($data);
                if($id){
                    return ['status'=> 1,'msg'=>'添加成功'];
                }else{
                    return ['status'=> 0,'msg'=>'添加失败'];
                }
            }else{
                return ['status'=> 0,'msg'=>'请选择文件'];
            }
        }
        return view('admin.baoan.add_cailiao', ['id' => $id,'uid'=>$uid]);
    }


    public function del_cailiao($id)
    {
        $re = db::table('baoan_file')->where('id',$id)->delete();
        if($re){
            return ['status'=> 1,'msg'=>'删除成功'];
        }else{
            return ['status'=> 0,'msg'=>'删除失败'];
        }
        //return redirect()->back();
    }

    public function kaohe($id,Request $request){
        if($request->rows) {
            $map['baoan_id'] = $id;
            $res = DB::table('baoan_kaohe')->where($map)->orderby('id','desc')->paginate($request->rows);
            $list = $res->items();
            $result['total'] = $res->total();
            $result['rows'] = $list;
            echo json_encode($result);
        }else{
            return view('admin.baoan.kaohe',['id'=>$id]);
        }
    }

    public function add_kaohe(Request $request,$id)
    {
        //考核项
        $count = db::table('baoan_kh')->where('is_show','1')->count();
        if($count > 0){
            $kaohexiang = db::table('baoan_kh')->where('is_show','1')->orderby('paixu','asc')->get();
            foreach ($kaohexiang as $k=>$v){
                if($v->field_type == 2){
                    $v->daan = db::table('baoan_kh_daan')->where('pid',$v->id)->orderby('id','asc')->get();
                }
            }
        }else{
            $kaohexiang = array();
        }
        if($request->isMethod('post')){
            $data = Input::except('_token','kaohe');
            $kaohexiang = Input::except('_token','kaoheren','kaohe_time','remark');
            $num = count($kaohexiang, true) - count($kaohexiang);
            if(Input::get('kaoheren') && Input::get('kaohe_time') && $num == $count){
                $data['baoan_id'] = $id;
                $data['user_id'] = Auth::guard('admin')->user()->id;
                $data['created_at'] = date('Y-m-d H:i:s',time());
                $data['updated_at'] = date('Y-m-d H:i:s',time());
                $total = '0';
                foreach ($kaohexiang['kaohe'] as $k=>$v){
                    $total = $v + $total;
                }
                $data['total'] = $total;
                if($data['total'] < 0.6*$count*10){
                    $data['is_hege'] = '2';
                }else{
                    $data['is_hege'] = '1';
                }
                //判断考核分数属于哪个等级并改变该保安等级
                $dengji = db::table('baoan_dengji')->get();
                foreach ($dengji as $v){
                    if($v->min_mark <= $total && $v->max_mark >= $total){
                        $obj['dengji'] = $v->id;
                    }
                }
                db::table('baoan')->where('id',$id)->update($obj);

                //保存基本信息
                $kh_id = DB::table('baoan_kaohe')->insertGetId($data);
                //保存考核项详情
                foreach ($kaohexiang['kaohe'] as $k=>$v){
                    $data2['field_name'] = $k;
                    $data2['field_content'] = getValue($k,'baoan_kh' ,'field_name' ,'field_content');
                    $map['pid'] = getValue($k,'baoan_kh' ,'field_name' ,'id');
                    $map['mark'] = $v;
                    $data2['val'] = db::table('baoan_kh_daan')->where($map)->value('val');
                    $data2['mark'] = $v;
                    $data2['kaohe_id'] = $kh_id;
                    db::table('baoan_kaohe_value')->insert($data2);
                }

                if($kh_id){
                    return ['status'=>1,'msg'=>'保存成功'];
                }else{
                    return ['status'=>0,'msg'=>'保存失败'];
                }
            }else{
                return ['status'=>0,'msg'=>'请填写完整后再提交'];
            }
        }
        return view('admin.baoan.add_kaohe', ['id'=>$id,'count'=>$count,'kaohexiang'=>$kaohexiang]);
    }

    public function edit_kaohe($id,Request $request)
    {
        $re = DB::table('baoan_kaohe')->where('id',$id)->first();
        $kaohexiang = db::table('baoan_kaohe_value')->where('kaohe_id',$id)->get();
        return view('admin.baoan.edit_kaohe', ['re' => $re,'id'=>$id,'kaohexiang'=>$kaohexiang]);
    }

    public function del_kaohe($id)
    {
        $re = db::table('baoan_kaohe')->where('id',$id)->delete();
        db::table('baoan_kaohe_value')->where('pid',$id)->delete();
        if($re){
            return ['status'=> 1,'msg'=>'删除成功'];
        }else{
            return ['status'=> 0,'msg'=>'删除失败'];
        }
        //return redirect()->back();
    }

    public function gudong($id,request $request)
    {
        if($request->rows) {
            $map['unit_id'] = $id;
            $res = DB::table('gudong')->where($map)->paginate($request->rows);
            $list = $res->items();
            $result['total'] = $res->total();
            $result['rows'] = $list;
            echo json_encode($result);
        }else{
            return view('admin.baoan.gudong', ['id'=>$id]);
        }
    }

    public function add_gudong(Request $request,$id)
    {
        if($request->isMethod('post')){
            $this->validate($request, [
                'unit_name' => 'required',
                'name' => 'required',
                'sex' => 'required',
                'birthday' => 'required',
                'nation' => 'required',
                'native_place' => 'required',
                'education' => 'required',
                'political_status' => 'required',
                'id_number' =>array('regex:/^(\d{15}$|^\d{18}$|^\d{17}(\d|X|x))$/'),
                'jine' => 'required',
                'bili' => 'required',
                'email' =>'nullable|email',
                'phone' =>array('regex:/^((0\d{2,3}-\d{7,8})|(1[3584]\d{9}))$/'),
            ],$this->messages('gudong'));
            $data = Input::except('_token');
            if($request['pic']){
                $images = $request['pic'];
                $filedir = "upload/baoan/".date('Y-m-d',time())."/";
                $extension = $images -> getClientOriginalExtension();
                $newImagesName=md5(time()).random_int(5,5).".".$extension;
                $images->move($filedir,$newImagesName);
                $data['pic'] = $filedir.$newImagesName;
            }
            $data['unit_id'] = $id;
            $data['user_id'] = Auth::guard('admin')->user()->id;
            $data['created_at'] = date('Y-m-d H:i:s',time());
            $data['updated_at'] = date('Y-m-d H:i:s',time());

            $re = DB::table('gudong')->insert($data);
            if($re){
                return ['msg'=>'保存成功'];
            }else{
                return ['msg'=>'保存失败'];
            }
            //return redirect('admin/units/baowei/'.$id);
        }
        //民族
        $nation = db::table('nation')->get();
        return view('admin.baoan.add_gudong', ['id'=>$id,'nation'=>$nation]);
    }

    public function edit_gudong($id,Request $request)
    {
        if($request->isMethod('post')){
            $this->validate($request, [
                'unit_name' => 'required',
                'name' => 'required',
                'sex' => 'required',
                'birthday' => 'required',
                'nation' => 'required',
                'native_place' => 'required',
                'education' => 'required',
                'political_status' => 'required',
                'id_number' =>array('regex:/^(\d{15}$|^\d{18}$|^\d{17}(\d|X|x))$/'),
                'jine' => 'required',
                'bili' => 'required',
                'email' =>'nullable|email',
                'phone' =>array('regex:/^((0\d{2,3}-\d{7,8})|(1[3584]\d{9}))$/'),
            ],$this->messages('gudong'));
            $data = Input::except('_token');
            if($request['pic']){
                $images = $request['pic'];
                $filedir = "upload/baoan/".date('Y-m-d',time())."/";
                $extension = $images -> getClientOriginalExtension();
                $newImagesName=md5(time()).random_int(5,5).".".$extension;
                $images->move($filedir,$newImagesName);
                $data['pic'] = $filedir.$newImagesName;
            }
            $data['user_id'] = Auth::guard('admin')->user()->id;
            $data['updated_at'] = date('Y-m-d H:i:s',time());
            $re = DB::table('gudong')->where('id',$id)->update($data);
            //$cid = DB::table('baoweirenyuan')->where('id',$id)->value('unit_id');
            if($re){
                return ['msg'=>'编辑成功'];
            }else{
                return ['msg'=>'编辑失败'];
            }
            //return redirect('admin/units/baowei/'.$cid);
        }
        $re = DB::table('gudong')->where('id',$id)->first();
        $nation = db::table('nation')->get();
        return view('admin.baoan.edit_gudong', ['re' => $re,'id'=>$id,'nation'=>$nation]);
    }

    public function del_gudong($id)
    {
        $re = db::table('gudong')->where('id',$id)->delete();
        if($re){
            return ['status'=> 1,'msg'=>'删除成功'];
        }else{
            return ['status'=> 0,'msg'=>'删除失败'];
        }
        //return redirect()->back();
    }

    public function guanli($id,request $request)
    {
        if($request->rows) {
            $map['unit_id'] = $id;
            $res = DB::table('guanli')->where($map)->paginate($request->rows);
            $list = $res->items();
            $result['total'] = $res->total();
            $result['rows'] = $list;
            echo json_encode($result);
        }else{
            return view('admin.baoan.guanli', ['id'=>$id]);
        }
    }

    public function add_guanli(Request $request,$id)
    {
        if($request->isMethod('post')){
            $this->validate($request, [
                'unit_name' => 'required',
                'name' => 'required',
                'sex' => 'required',
                'birthday' => 'required',
                'nation' => 'required',
                'native_place' => 'required',
                'education' => 'required',
                'political_status' => 'required',
                'id_number' =>array('regex:/^(\d{15}$|^\d{18}$|^\d{17}(\d|X|x))$/'),
                'email' =>'nullable|email',
                'phone' =>array('regex:/^((0\d{2,3}-\d{7,8})|(1[3584]\d{9}))$/'),
            ],$this->messages('guanli'));
            $data = Input::except('_token');
            if($request['pic']){
                $images = $request['pic'];
                $filedir = "upload/baoan/".date('Y-m-d',time())."/";
                $extension = $images -> getClientOriginalExtension();
                $newImagesName=md5(time()).random_int(5,5).".".$extension;
                $images->move($filedir,$newImagesName);
                $data['pic'] = $filedir.$newImagesName;
            }
            $data['unit_id'] = $id;
            $data['user_id'] = Auth::guard('admin')->user()->id;
            $data['created_at'] = date('Y-m-d H:i:s',time());
            $data['updated_at'] = date('Y-m-d H:i:s',time());

            $re = DB::table('guanli')->insert($data);
            if($re){
                return ['msg'=>'保存成功'];
            }else{
                return ['msg'=>'保存失败'];
            }
            //return redirect('admin/units/baowei/'.$id);
        }
        //民族
        $nation = db::table('nation')->get();
        return view('admin.baoan.add_guanli', ['id'=>$id,'nation'=>$nation]);
    }

    public function edit_guanli($id,Request $request)
    {
        if($request->isMethod('post')){
            $this->validate($request, [
                'unit_name' => 'required',
                'name' => 'required',
                'sex' => 'required',
                'birthday' => 'required',
                'nation' => 'required',
                'native_place' => 'required',
                'education' => 'required',
                'political_status' => 'required',
                'id_number' =>array('regex:/^(\d{15}$|^\d{18}$|^\d{17}(\d|X|x))$/'),
                'email' =>'nullable|email',
                'phone' =>array('regex:/^((0\d{2,3}-\d{7,8})|(1[3584]\d{9}))$/'),
            ],$this->messages('guanli'));
            $data = Input::except('_token');
            if($request['pic']){
                $images = $request['pic'];
                $filedir = "upload/baoan/".date('Y-m-d',time())."/";
                $extension = $images -> getClientOriginalExtension();
                $newImagesName=md5(time()).random_int(5,5).".".$extension;
                $images->move($filedir,$newImagesName);
                $data['pic'] = $filedir.$newImagesName;
            }
            $data['user_id'] = Auth::guard('admin')->user()->id;
            $data['updated_at'] = date('Y-m-d H:i:s',time());
            $re = DB::table('guanli')->where('id',$id)->update($data);
            //$cid = DB::table('baoweirenyuan')->where('id',$id)->value('unit_id');
            if($re){
                return ['msg'=>'编辑成功'];
            }else{
                return ['msg'=>'编辑失败'];
            }
            //return redirect('admin/units/baowei/'.$cid);
        }
        $re = DB::table('guanli')->where('id',$id)->first();
        $nation = db::table('nation')->get();
        return view('admin.baoan.edit_guanli', ['re' => $re,'id'=>$id,'nation'=>$nation]);
    }

    public function del_guanli($id)
    {
        $re = db::table('guanli')->where('id',$id)->delete();
        if($re){
            return ['status'=> 1,'msg'=>'删除成功'];
        }else{
            return ['status'=> 0,'msg'=>'删除失败'];
        }
        //return redirect()->back();
    }

    public function gongsi_kaohe($id,Request $request){
        if($request->rows) {
            $map['unit_id'] = $id;
            $res = DB::table('baoangongsi_kaohe')->where($map)->paginate($request->rows);
            $list = $res->items();
            foreach ($list as $k=>$v){
                if($v->is_hege == 1){
                    $list[$k]->is_hege = '合格';
                }else{
                    $list[$k]->is_hege = '不合格';
                }
            }
            $result['total'] = $res->total();
            $result['rows'] = $list;
            echo json_encode($result);
        }else{
            return view('admin.baoan.gongsi_kaohe',['id'=>$id]);
        }
    }

    public function add_gongsi_kaohe(Request $request,$id)
    {
        if($request->isMethod('post')){
            $this->validate($request, [
                'kaoheren' => 'required',
                'kaohe_time' => 'required',
                'yanzhongshigu' => 'required',
                'yibanshigu' => 'required',
            ],$this->messages('kaohe'));
            $data = Input::except('_token');
            $data['unit_id'] = $id;
            $data['user_id'] = Auth::guard('admin')->user()->id;
            $data['created_at'] = date('Y-m-d H:i:s',time());
            $data['updated_at'] = date('Y-m-d H:i:s',time());
            $data['yanzhongshigu'] = (int)(Input::get('yanzhongshigu'));
            $data['yibanshigu'] = (int)(Input::get('yibanshigu'));
            $data['total'] = 100-(Input::get('yanzhongshigu') * 40 + Input::get('yibanshigu') * 20);
            if($data['total'] < 60){
                $data['is_hege'] = '2';
                $data2['is_hege'] = '2';
                DB::table('baoan_company')->where('id',$id)->update($data2);
            }else{
                $data['is_hege'] = '1';
                $data2['is_hege'] = '1';
                DB::table('baoan_company')->where('id',$id)->update($data2);
            }
            $re = DB::table('baoangongsi_kaohe')->insert($data);
            if($re){
                return ['status'=>1,'msg'=>'保存成功'];
            }else{
                return ['status'=>0,'msg'=>'保存失败'];
            }
        }
        return view('admin.baoan.add_gongsi_kaohe', ['id'=>$id]);
    }

    public function edit_gongsi_kaohe($id,Request $request)
    {
        $re = DB::table('baoangongsi_kaohe')->where('id',$id)->first();
        return view('admin.baoan.edit_gongsi_kaohe', ['re' => $re,'id'=>$id]);
    }

    public function del_gongsi_kaohe($id)
    {
        $re = db::table('baoangongsi_kaohe')->where('id',$id)->delete();
        if($re){
            return ['status'=> 1,'msg'=>'删除成功'];
        }else{
            return ['status'=> 0,'msg'=>'删除失败'];
        }
        //return redirect()->back();
    }

    //打印重点人员
    public function print_baoangongsi($id)
    {
        $re = DB::table('baoan_company')->where('id',$id)->first();
        $re->fanwei = explode(",",$re->fanwei);

        //市
        $city = db::table('area')->where('dengji','=','1')->orderby('id')->get();
        //股东
        $gudong = db::table('gudong')->where('unit_id',$id)->get();
        $gudong_count = db::table('gudong')->where('unit_id',$id)->count();
        //管理
        $guanli = db::table('guanli')->where('unit_id',$id)->get();
        $guanli_count = db::table('guanli')->where('unit_id',$id)->count();
        return view('admin.baoan.print_baoangongsi', ['re' => $re,'city' => $city,'id' => $id,'gudong'=>$gudong,'gudong_count'=>$gudong_count,'guanli'=>$guanli,'guanli_count'=>$guanli_count]);
    }

    public function print_faren($id,Request $request)
    {
        $re = DB::table('baoan_faren')->where('id',$id)->first();
        return view('admin.baoan.print_faren', ['re' => $re,'id' => $id]);
    }

    public function print_baoan($id,Request $request)
    {
        $re = DB::table('baoan')->where('id',$id)->first();
        return view('admin.baoan.print_baoan', ['re' => $re,'id'=>$id]);
    }

    //导出
    public function export_baoan_company(request $request){
        //如果是民警登录，只能查看自己辖区的单位
        if(Auth::guard('admin')->user()->org_id != null && Auth::guard('admin')->user()->dengji == 4){
            $map['baoan_company.org_id'] = Auth::guard('admin')->user()->org_id;
        }
        //如果是企业用户
        if(Auth::guard('admin')->user()->role_id == 22){
            $map['baoan_company.id'] = Auth::guard('admin')->user()->unit_id;
        }
        if($request->city != null){
            if($request->city == 0){

            }else{
                $map['baoan_company.city'] = $request->city;
            }
        }
        if($request->area){
            $map['baoan_company.area'] = $request->area;
        }
        if($request->org_id){
            $map['baoan_company.org_id'] = $request->org_id;
        }
        if($request->name){
            $map[] = array('baoan_company.name','like','%'.$request->name.'%');
        }
        if($request->lianxiren){
            $map['baoan_company.lianxiren'] = $request->lianxiren;
        }
        $map['baoan_company.is_del'] = '0';
        $res = DB::table('baoan_company')
            ->where($map)
            ->leftJoin('area as a', 'baoan_company.city', '=', 'a.id')
            ->leftJoin('area as b', 'baoan_company.area', '=', 'b.id')
            ->leftJoin('area as c', 'baoan_company.org_id', '=', 'c.id')
            ->leftJoin('admin_users as e', 'baoan_company.user_id', '=', 'e.id')
            ->select('baoan_company.*', 'a.name as city', 'b.name as area', 'c.name as org_id', 'e.name as user_id')
            ->get();
        $cellData[] = ['市','区','所属派出所','企业性质','单位名','详细地址','联系人','联系电话','是否合格'];
        foreach ($res as $k=>$v){
            if($v->is_hege == 1){
                $v->is_hege = '合格';
            }elseif($v->is_hege == 2){
                $v->is_hege = '不合格';
            }else{
                $v->is_hege = '暂未考核';
            }
            $cellData[$k+1] = [$v->city,$v->area,$v->org_id,$v->xingzhi,$v->name,$v->address,$v->lianxiren,$v->phone,$v->is_hege];
        }
        Excel::create('保安公司导出_'.date('YmdHis',time()),function($excel) use ($cellData){
            $excel->sheet('score', function($sheet) use ($cellData){
                $sheet->rows($cellData);
            });
        })->export('xls');
    }


}
